package com.ebook.service;

import com.ebook.entity.Book;
import com.ebook.entity.User;
import com.ebook.repository.BookRepository;
import com.ebook.repository.UserRepository;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class BookService {
    
    @Autowired
    private BookRepository bookRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Value("${app.upload.dir:uploads}")
    private String uploadDir;
    
    private final Tika tika = new Tika();
    
    public Book uploadBook(MultipartFile file, String title, String author, String category, String username) throws IOException {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        // 创建上传目录 - 使用项目根目录的绝对路径
        String projectRoot = System.getProperty("user.dir");
        Path baseUploadPath = Paths.get(projectRoot, uploadDir);
        Path userUploadPath = baseUploadPath.resolve(username);
        
        // 确保目录存在
        if (!Files.exists(baseUploadPath)) {
            Files.createDirectories(baseUploadPath);
            System.out.println("创建基础上传目录: " + baseUploadPath.toString());
        }
        
        if (!Files.exists(userUploadPath)) {
            Files.createDirectories(userUploadPath);
            System.out.println("创建用户上传目录: " + userUploadPath.toString());
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null || originalFilename.trim().isEmpty()) {
            throw new IOException("文件名无效");
        }
        
        String fileExtension = "";
        int lastDotIndex = originalFilename.lastIndexOf(".");
        if (lastDotIndex > 0) {
            fileExtension = originalFilename.substring(lastDotIndex);
        }
        
        String uniqueFilename = UUID.randomUUID().toString() + fileExtension;
        
        // 保存文件
        Path filePath = userUploadPath.resolve(uniqueFilename);
        System.out.println("保存文件到: " + filePath.toString());
        
        try {
            file.transferTo(filePath.toFile());
            System.out.println("文件保存成功");
            
            // 验证文件确实被保存
            if (!Files.exists(filePath)) {
                throw new IOException("文件保存失败：文件不存在");
            }
            
            long savedFileSize = Files.size(filePath);
            System.out.println("保存的文件大小: " + savedFileSize + " bytes");
            
        } catch (Exception e) {
            System.err.println("文件保存失败: " + e.getMessage());
            throw new IOException("文件保存失败: " + e.getMessage(), e);
        }
        
        // 简化文件类型检测，避免使用可能已读取的InputStream
        String fileType = getFileType(file.getContentType(), fileExtension);
        System.out.println("检测到的文件类型: " + fileType);
        
        // 创建书籍记录
        Book book = new Book();
        book.setTitle(title != null && !title.trim().isEmpty() ? title.trim() : originalFilename);
        book.setAuthor(author != null && !author.trim().isEmpty() ? author.trim() : null);
        book.setCategory(category != null && !category.trim().isEmpty() ? category.trim() : null);
        book.setFileName(originalFilename);
        book.setFilePath(filePath.toString());
        book.setFileSize(file.getSize());
        book.setFileType(fileType);
        book.setUser(user);
        
        Book savedBook = bookRepository.save(book);
        System.out.println("书籍记录保存成功，ID: " + savedBook.getId());
        
        return savedBook;
    }
    
    private String getFileType(String mimeType, String fileExtension) {
        // 优先根据文件扩展名判断
        if (fileExtension != null) {
            String ext = fileExtension.toLowerCase();
            if (ext.equals(".pdf")) {
                return "PDF";
            } else if (ext.equals(".epub")) {
                return "EPUB";
            } else if (ext.equals(".txt")) {
                return "TXT";
            }
        }
        
        // 备用：根据MIME类型判断
        if (mimeType != null) {
            String mime = mimeType.toLowerCase();
            if (mime.contains("pdf")) {
                return "PDF";
            } else if (mime.contains("epub")) {
                return "EPUB";
            } else if (mime.contains("text")) {
                return "TXT";
            }
        }
        
        return "UNKNOWN";
    }
    
    public List<Book> getUserBooks(String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return bookRepository.findByUserOrderByCreatedAtDesc(user);
    }
    
    public List<Book> getUserBooksByCategory(String username, String category) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return bookRepository.findByUserAndCategoryOrderByCreatedAtDesc(user, category);
    }
    
    public List<String> getUserCategories(String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return bookRepository.findCategoriesByUser(user);
    }
    
    public List<Book> searchBooks(String username, String keyword) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return bookRepository.searchBooks(user, keyword);
    }
    
    public Optional<Book> getBookById(Long id, String username) {
        if (username == null || username.trim().isEmpty()) {
            System.err.println("用户名为空");
            return Optional.empty();
        }
        
        User user = userRepository.findByUsername(username)
                .orElse(null);
        
        if (user == null) {
            System.err.println("用户不存在: " + username);
            return Optional.empty();
        }
        
        Optional<Book> book = bookRepository.findById(id);
        if (book.isPresent()) {
            Book bookEntity = book.get();
            if (bookEntity.getUser().getId().equals(user.getId())) {
                System.out.println("找到书籍，ID: " + id + ", 用户: " + username);
                return book;
            } else {
                System.err.println("用户无权限访问书籍，书籍ID: " + id + ", 用户: " + username);
            }
        } else {
            System.err.println("书籍不存在，ID: " + id);
        }
        
        return Optional.empty();
    }
    
    public boolean deleteBook(Long id, String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        Optional<Book> book = bookRepository.findById(id);
        if (book.isPresent() && book.get().getUser().getId().equals(user.getId())) {
            // 删除文件
            try {
                Path filePath = Paths.get(book.get().getFilePath());
                if (Files.exists(filePath)) {
                    Files.delete(filePath);
                    System.out.println("删除文件: " + filePath.toString());
                }
            } catch (IOException e) {
                System.err.println("删除文件失败: " + e.getMessage());
                // 不抛出异常，继续删除数据库记录
            }
            
            // 删除记录
            bookRepository.deleteById(id);
            return true;
        }
        return false;
    }
    
    public Book updateBook(Long id, String title, String author, String category, String username) {
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        
        Optional<Book> bookOpt = bookRepository.findById(id);
        if (bookOpt.isPresent() && bookOpt.get().getUser().getId().equals(user.getId())) {
            Book book = bookOpt.get();
            book.setTitle(title);
            book.setAuthor(author);
            book.setCategory(category);
            return bookRepository.save(book);
        }
        throw new RuntimeException("书籍不存在或无权限");
    }
}